#include "stdafx.h"
#include "Material.h"

using namespace MomogenkyouSystem;

Material::Material()
:	Effect(NULL),  Param_StandardGlobals(NULL)
{
	//matWorld = MomogenkyouHelper::MATRIX_IDENTITY;
}

Material::~Material()
{
	if(Effect != NULL)	Effect->Release();
}

HRESULT	Material::PrepareEffectFile(const std::string & Directory, const std::string & FilePath, D3DXEFFECTINSTANCE * pEffectBuffer)
{
	HRESULT	_Result = S_OK;
	_Result = D3DXCreateEffectFromFileA(GraphicsSystem::Device, FilePath.c_str(), NULL, NULL, NULL, NULL, &Effect, NULL);
	ASSERT(_Result == S_OK, "Unable to load Effect");

	D3DXHANDLE			_Handle;
	D3DXPARAMETER_DESC	_Param_DESC;
	//	Set all embeded default values, except abnormal types
	for(size_t j = 0; j < pEffectBuffer->NumDefaults; j++)
	{
		_Handle = Effect->GetParameterByName(NULL, pEffectBuffer->pDefaults[j].pParamName);
		if(_Handle == NULL) continue;

		Effect->GetParameterDesc(_Handle, &_Param_DESC);

		if( _Param_DESC.Type == D3DXPT_BOOL		||
			_Param_DESC.Type == D3DXPT_INT		||
			_Param_DESC.Type == D3DXPT_FLOAT)
		{
			Effect->SetValue(pEffectBuffer->pDefaults[j].pParamName, pEffectBuffer->pDefaults[j].pValue, pEffectBuffer->pDefaults[j].NumBytes);
		}
		else if(_Param_DESC.Type == D3DXPT_TEXTURE)
		{
			//	Set texture
			std::string	_TexturePath	=	Directory + (char *)pEffectBuffer->pDefaults[j].pValue;
			TEXTURE _Texture = NULL;
			_Result = D3DXCreateTextureFromFileA(GraphicsSystem::Device, _TexturePath.c_str(),     &_Texture);
			ASSERT(_Result == S_OK, "Unable to load Texture");
			Effect->SetTexture(pEffectBuffer->pDefaults[j].pParamName, _Texture);
		}
	}

	return _Result;
}

void	Material::PrepareStandardGlobalParams(MATRIX * pmatView, MATRIX * pmatProjection, float4 * pvSunPosition)
{
	Effect->BeginParameterBlock();
	
	//Effect->SetMatrix("matWorld",		&matWorld);
	Effect->SetMatrix("matView",		pmatView);
	Effect->SetMatrix("matProjection",	pmatProjection);
	Effect->SetVector("vSunPosition",	pvSunPosition);
	//	More to  be added, Includes cube map etc

	Param_StandardGlobals = Effect->EndParameterBlock();
}